package com.hongxun.design.jungong.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.hongxun.design.MyApp;
import com.hongxun.design.R;
import com.hongxun.design.activitys.RegeditActivity;
import com.hongxun.design.constant.Constant;
import com.hongxun.design.fragments.BaseFragment;
import com.hongxun.design.jungong.activity.ProRecAndPicActivity;
import com.hongxun.design.jungong.adapter.FragmentPhotoAdapter;
import com.hongxun.design.jungong.model.SspPhoto;
import com.hongxun.design.jungong.model.SspRecord;
import com.hongxun.design.mytools.CheckUtil;
import com.hongxun.design.mytools.IconSourse;
import com.hongxun.design.mytools.MString;
import com.hongxun.design.mytools.SetTypeface;
import com.hongxun.design.mytools.ShardPreferencesTool;
import com.hongxun.design.mytools.ToastShow;
import com.hongxun.design.ui.dialogstyle.MyDialog;
import com.hongxun.design.ui.myiossheet.ActionSheet;
import com.hongxun.design.ui.ui_listview.Swipemenulistview.SwipeMenu;
import com.hongxun.design.ui.ui_listview.Swipemenulistview.SwipeMenuCreator;
import com.hongxun.design.ui.ui_listview.Swipemenulistview.SwipeMenuItem;
import com.hongxun.design.ui.ui_listview.Swipemenulistview.SwipeMenuListView;
import com.hongxun.design.ui.ui_listview.refreshlist.SwipeRefreshListView;
import com.hongxun.design.utils.DensityUtil;
import com.hongxun.design.utils.camerautil.CameraUtil;
import com.hongxun.design.utils.fastjson.FastJsonUtil;
import com.hongxun.design.utils.fileutil.FileUtil;

import java.util.ArrayList;
import java.util.List;

import static android.app.Activity.RESULT_OK;

/**
 * Created by cqcqwucp 照片列表显示
 */
public class FragmentPhotoListView extends BaseFragment implements View.OnClickListener {
    //控件
    private View view;
    private TextView tv1, tv2, tv5;
    private SwipeRefreshListView listView;
    //数据
    private List<SspPhoto> photoListY, photoListN;
    private FragmentPhotoAdapter adapter;
    private SspRecord record10;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1://删除一张照片
                    delPhoto((SspPhoto) msg.obj);
                    break;
                case 2://查看大图
                    msg.arg2 = -2;
                    MyDialog.showBigImgDialog(getActivity(), record10, msg);
                    break;
            }
        }
    };

    public FragmentPhotoListView() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.jg_fragmnet_photo_lv, container, false);
        findViewById();
        return view;
    }

    private void findViewById() {
        tv1 = (TextView) view.findViewById(R.id.photolv_tv1);
        tv2 = (TextView) view.findViewById(R.id.photolv_tv2);
        view.findViewById(R.id.photolv_tv4).setOnClickListener(this);
        tv5 = (TextView) view.findViewById(R.id.photolv_tv5);

        SetTypeface.set(tv1, IconSourse.BACK);
        tv1.setOnClickListener(this);

        record10 = (SspRecord) getArguments().getSerializable(MString.key);
        tv2.setText(record10.getPname());
        tv5.setText(record10.getPileseat() + "" + record10.getKwords());
        photoListY = new ArrayList<>();
        photoListN = new ArrayList<>();

        listView = (SwipeRefreshListView) view.findViewById(R.id.photolv_srlv1);
        adapter = new FragmentPhotoAdapter(getActivity(), photoListY);
        adapter.setHandlerAndInx(handler, 1, 2);
        listView.setAdapter(adapter);
        listView.setFragment(this);
        listView.setCanScroll(false);

        listView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                listView.setRefreshing(false);
            }
        });
        SwipeMenuCreator creator = new SwipeMenuCreator() {
            @Override
            public void create(SwipeMenu menu) {
                SwipeMenuItem deleteItem = new SwipeMenuItem(getActivity());
                deleteItem.setBackground(R.color.red);
                deleteItem.setWidth(DensityUtil.dip2px(getActivity(), 90));
                deleteItem.setIcon(R.mipmap.ic_delete);
                menu.addMenuItem(deleteItem);
            }
        };
        listView.setMenuCreator(creator, new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public void onMenuItemClick(int position, SwipeMenu menu, int index) {
                List<String> list = new ArrayList<>();
                list.add("删除提示");
                list.add("是否删除照片");
                list.add("否");
                list.add("是");
                MyDialog.recordDel(getActivity(), list, handler, photoListY.get(position), 0, 1);
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        showListPhoto();
    }

    private void showListPhoto() {
        photoListY.clear();
        photoListN.clear();
        String photots = ShardPreferencesTool.getrecord(getActivity(), record10.getGuid(), "");
        List<SspPhoto> photoList = JSON.parseArray(photots, SspPhoto.class);
        if (photoList != null)
            for (SspPhoto photo : photoList) {
                if (!photo.getIsdel().equalsIgnoreCase("删除")) photoListY.add(photo);
                else photoListN.add(photo);
            }
        listView.update();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.photolv_tv1:
                backtolastview();
                break;
            case R.id.photolv_tv4:
                openSheet(getActivity(), "选择方式", "相册", "拍照");
                break;
        }
    }

    private void backtolastview() {
        ((ProRecAndPicActivity) getActivity()).onBack(0);
    }

    //照片在onResume之前
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            String path;
            switch (requestCode) {
                case 1://拍照
                    path = Environment.getExternalStorageDirectory() + "/" + Constant.TMP_PATH;
                    savePhoto(path);
                    break;
                case 2://相册
                    path = CheckUtil.getFilePath(getActivity(), data.getData());
                    savePhoto(path);
                    break;
            }
        }
    }

    private void savePhoto(String path) {
        String millis = String.valueOf(System.currentTimeMillis());
        SspPhoto photo = new SspPhoto();
        photo.setId(millis);
        photo.setGuid(MString.getMyUUID());
        photo.setSid(MyApp.currProject.getStage_id());
        photo.setRguid(record10.getGuid());

        //下一界面设置
//        photo.setPlistone(record10.getPlist());
//        photo.setRemarks("暂无，未设置");

        photo.setLongitude(String.valueOf(MyApp.bdLocation.getLongitude()));
        photo.setLatitude(String.valueOf(MyApp.bdLocation.getLatitude()));
        photo.setFounderid(MyApp.userInfo.getUser_id());
        photo.setFoundertime(millis);
        String name = path.substring(path.lastIndexOf("/") + 1);
        photo.setImgname(name);
        photo.setImgaddress(path);
        photo.setImgurl("");
        photo.setIsdel("新增");
        photo.setLasttime(millis);
        //跳转到照片水印设置界面
        ((ProRecAndPicActivity) getActivity()).onBack(2, record10, photo, 1);
    }

    //修改照片数据状态
    private void delPhoto(SspPhoto photo) {
        if (photo.getIsdel().equalsIgnoreCase("已同步")) {
            photo.setIsdel("删除");
            photoListN.add(photo);
        } else {
            photoListY.remove(photo);
        }
        listView.update();
        FileUtil.deleteFile(photo.getImgaddress());
        List<SspPhoto> photoList11 = new ArrayList<>();
        photoList11.addAll(photoListY);
        photoList11.addAll(photoListN);
        saveToXml(FastJsonUtil.beanToJson(photoList11), record10.getGuid());
        UpdataRec();
        ToastShow.showShort(getActivity(),"删除成功");
    }

    //修改记录数据状态
    private void UpdataRec() {
        List<SspRecord> recordList = new ArrayList<>();
        String jsonRec = ShardPreferencesTool.getrecord(getActivity(), MyApp.currProject.getStage_id(), "");
        if (!TextUtils.isEmpty(jsonRec)) {
            List<SspRecord> records = JSON.parseArray(jsonRec, SspRecord.class);
            if (records != null) {
                for (SspRecord record : records) {
                    if (!record.getIsdel().equalsIgnoreCase("删除")) {
                        if (record.getId().equals(record10.getId())) {
                            if (record10.getIsdel().equals("已同步")) {
                                record.setIsdel("修改");
                                record.setLasttime(String.valueOf(System.currentTimeMillis()));
                                recordList.add(0, record);//最新数据靠前存取
                            } else {
                                record.setLasttime(String.valueOf(System.currentTimeMillis()));
                                recordList.add(0, record);//最新数据靠前存取
                            }
                        } else {
                            recordList.add(record);
                        }
                    }
                }
            }
        }
        saveToXml(FastJsonUtil.beanToJson(recordList), MyApp.currProject.getStage_id());
    }

    private void openSheet(Activity activity, final String... titles) {
        activity.setTheme(R.style.ActionSheetStyleIOS7);
        ActionSheet menuView = new ActionSheet(activity);
        menuView.setCancelButtonTitle("取消");// before add items
        menuView.addItems(titles);
        menuView.setItemClickListener(new ActionSheet.MenuItemClickListener() {
            @Override
            public void onItemClick(int itemPosition) {
                if (itemPosition == 0) return;
                if (itemPosition == 1) {
                    CameraUtil.pickPhoto(RegeditActivity.Code_Select);//相册
                } else {
                    CameraUtil.openCamera(RegeditActivity.Code_Pick);//拍照
                }
            }
        });
        menuView.setCancelableOnTouchMenuOutside(true);
        menuView.showMenu();
    }

    //保存数据
    private void saveToXml(String json, String key) {
        ShardPreferencesTool.saverecord(getActivity(), key, json);
    }

    public void onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) backtolastview();
    }
}
